import React, { useEffect, useState } from 'react';
import { listNotificationsService, markNotificationService, markAllNotificationsService } from '../api/NotificationApi';
import { Button, Pagination, message, Spin } from 'antd';
import './NotificationList.css';

const PAGE_SIZE = 10;

const NotificationList = () => {
  const [notifications, setNotifications] = useState([]);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);

  // 获取用户ID（假设从localStorage获取）
  const userId = localStorage.getItem('userId');

  const fetchNotifications = async (pageNum = 1) => {
    setLoading(true);
    try {
      const res = await listNotificationsService(userId, pageNum, PAGE_SIZE);
      setNotifications(res.list || res); // 兼容你的返回结构
      setTotal(res.total || res.length || 0);
    } catch (e) {
      message.error('获取通知失败');
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchNotifications(page);
    // eslint-disable-next-line
  }, [page]);

  const handleMarkRead = async (id) => {
    await markNotificationService(id);
    message.success('已标记为已读');
    fetchNotifications(page);
  };

  const handleMarkAll = async () => {
    await markAllNotificationsService();
    message.success('全部已标记为已读');
    fetchNotifications(page);
  };

  return (
    <div className="notification-list-container">
      <div className="notification-list-header">
        <h2>通知中心</h2>
        <Button className="mark-all-btn" onClick={handleMarkAll}>全部已读</Button>
      </div>
      <Spin spinning={loading}>
        <ul className="notification-list">
          {notifications.length === 0 && <li className="empty-tip">暂无通知</li>}
          {notifications.map(item => (
            <li key={item.id} className={`notification-item ${item.isRead ? 'read' : 'unread'}`}>
              <div className="notification-content">{item.content}</div>
              <div className="notification-meta">
                <span className="notification-time">{new Date(item.createdTime).toLocaleString()}</span>
                {!item.isRead && (
                  <Button
                    size="small"
                    className="mark-read-btn"
                    onClick={() => handleMarkRead(item.id)}
                  >
                    已读
                  </Button>
                )}
              </div>
            </li>
          ))}
        </ul>
        <Pagination
          className="notification-pagination"
          current={page}
          pageSize={PAGE_SIZE}
          total={total}
          onChange={setPage}
          showSizeChanger={false}
        />
      </Spin>
    </div>
  );
};

export default NotificationList;